# TriggerSwitchD, executes commands to activate/deactive remote switches.
# (c) Copyright 2010 Pontus Strömdahl, AdhocSkill. 
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


$LOAD_PATH.push File.join(File.dirname(__FILE__),"protocol")
require "null_protocol"
require "not_connected" 
require "protocol_loader"

# The Tellstick module represents the virtual equivalent of the 
# hardware usb dongle. Use #create with TellstickIO.new as the output

module Tellstick

  #takes any kind of IO, but specifically TellstickIO, as output
  #and the name of the transmission protocol. It returns an 
  #instance of Tellstick.
  #
  #The protocol is mixed into Tellstick with the methods:
  #* turn_on
  #* turn_off
  #* teach <i>(if the protocol supports it)</i>
  def create(output,protocol_name="plain_text")
    protocol = load(protocol_name)
    dongle = Tellstick.new(output)
    if connection_not_needed_for(output) or output.connected?
      dongle.extend protocol
    else
      dongle.extend NotConnected
    end
    dongle
  end
  module_function :create
  
  # use create to instasiate
  class Tellstick
    def initialize(output) #:nodoc:
      @output = output
    end
  end
  
  private
  def self.connection_not_needed_for(output)
    not output.methods.include?("connected?")
  end
  def self.load(name)
    $protocol ||= Hash.new(NullProtocol)
    filename = File.join(File.dirname(__FILE__),"protocol",name)
    require filename if File.exists?("#{filename}.rb")
    return $protocol[name]
  end
end
